package ca.dominion.heritageQuiz.quiz {
	
	import ca.dominion.heritageQuiz.events.RadioSelectionEvent;
	import ca.dominion.heritageQuiz.form.UserInfoForm;
	import ca.dominion.heritageQuiz.globals.*;
	import ca.dominion.heritageQuiz.interactiveComponents.NavigationButton;
	import ca.dominion.heritageQuiz.quiz.components.*;
	import ca.dominion.heritageQuiz.quiz.data.*;
	import ca.dominion.heritageQuiz.text.EmbeddedText;
	
	import caurina.transitions.Tweener;
	
	import flash.display.Sprite;
	import flash.events.*;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	/**
	 * 
	 * @author ghostmonk
	 * 
	 */
	public class Quiz extends Sprite {
		
		
		
		private var _userForm:UserInfoForm;
		
		private var _currentChoice:int;
		private var _currentQuestion:int;
		private var _totalQuestions:int;
		private var _questions:Array;
		
		private var _questionTrackerField:EmbeddedText;
		private var _questionField:EmbeddedText;
		private var _responseDisplay:ResponseView;
		private var _results:Results;
		
		private var _animatedImage:AnimatedImage;
		private var _multipleChoiceView:MultipleChoiceView;
		private var _navBtn:NavigationButton;
		
		private var _isActive:Boolean;
		
		
		
		/**
		 * 
		 * 
		 */
		public function Quiz() {
			
			_isActive = false;
			_userForm = new UserInfoForm();
			
			_animatedImage = new AnimatedImage( Config.IMAGE_WIDTH, Config.IMAGE_HEIGHT );
			_questionTrackerField = new EmbeddedText( "Lucida Sans", Config.PROJECT_XML.headerText1.@size, Config.PROJECT_XML.headerText1.@color, true );
			_questionField = new EmbeddedText( "Lucida Sans", Config.PROJECT_XML.headerText2.@size, Config.PROJECT_XML.headerText2.@color );
			_navBtn = new NavigationButton( );
			_responseDisplay = new ResponseView( );
			
			_multipleChoiceView = new MultipleChoiceView( );
			_results = new Results( );
			
			_navBtn.addEventListener( InteractiveEvent.SUBMIT_CHOICE, onSubmitChoice );
			_navBtn.addEventListener( InteractiveEvent.NEXT_QUESTION, onNextQuestion );
			_navBtn.addEventListener( InteractiveEvent.GET_RESULTS, onGetResults );
			
			_multipleChoiceView.addEventListener( RadioSelectionEvent.RADIO_SELECTION, onRadioSelection );
			_multipleChoiceView.addEventListener( InteractiveEvent.BUILD_OUT_COMPLETE, onBuildOutComplete );
			
		}
		
		
		
		/**
		 * 
		 * @param questions
		 * 
		 */
		public function init( questions:QuestionArray ):void {
			
			if( questions.length < 1 )
			{
				throw( new Error( "You must have at least one question in your Questions array" ) );
			}
			questions.lock();
			_questions = questions.array;
			_totalQuestions = _questions.length;
			_currentQuestion = 0;
			addEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
			
			_multipleChoiceView.init( Question( _questions[0] ).options );
			_results.init( _totalQuestions );
			
		}
		
		
		
		/**
		 * 
		 * @param node
		 * 
		 */
		public function setQuestion( node:int ):void {
			
			addChild( _multipleChoiceView );
			var currentQuestion:Question = _questions[node]; 
			_animatedImage.load( currentQuestion.imageURL );
			_multipleChoiceView.setView( currentQuestion.options );
			
			_questionField.testMetrics( currentQuestion.text, 75, Config.PROJECT_XML.headerText2.@size );
			_multipleChoiceView.y = _questionField.y + _questionField.fieldHeight - 10;
			
			Tweener.addTween(
                _questionTrackerField, {
                    _text:Config.COPY.question.toString() + " " + ( _currentQuestion + 1 ) + "/" + _totalQuestions, 
                    time:0.5, 
                    transition:'linear'
                }
            );
		
		}
		
		
		
		private function onAddedToStage( e:Event ):void {
			
			positionAssets( );
			addChild( _animatedImage );
			addChild( _questionTrackerField );
			addChild( _questionField );
			addChild( _responseDisplay );
			_isActive ? setQuestion( _currentQuestion ) : setFormView();
			removeEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
			
		}
		
		
		
		private function setFormView():void {
			
			_isActive = true;
			_animatedImage.load( _questions[0].imageURL );
			_questionField.testMetrics( Config.COPY.formTitle.toString(), 75, Config.PROJECT_XML.headerText2.@size );
			addChild( _userForm );
			_userForm.addEventListener( Event.COMPLETE, onFormFinished );
			_userForm.x = _questionField.x;
			_userForm.y = _questionField.y + _questionField.fieldHeight + 10;
			
		}
		
		
		
		private function onFormFinished( e:Event ):void {
			
			setQuestion( 0 );
		}
		
		
		
		private function positionAssets( ):void {
			
			_animatedImage.x = Config.IMAGE_WIDTH/2 + 20;
			_animatedImage.y = stage.stageHeight/2;
			_questionTrackerField.x = _animatedImage.x - Config.IMAGE_WIDTH/2;
			_questionTrackerField.y = 20;
			_questionField.width = 340;
			_questionField.x = _animatedImage.x + Config.IMAGE_WIDTH/2 + 20;
			_questionField.y = _animatedImage.y - Config.IMAGE_HEIGHT/2;
			_multipleChoiceView.x = _questionField.x;
			_multipleChoiceView.y = _questionField.y + _questionField.fieldHeight + 20;
			_responseDisplay.x = _multipleChoiceView.x;
			
		}
		
		
		
		private function onRadioSelection( e:RadioSelectionEvent ):void {
			
			_currentChoice = e.node;
			
			if( !_navBtn.buttonMode ) {
				addChild( _navBtn );
				_navBtn.x = _questionField.x + 50;
				_navBtn.y = _multipleChoiceView.y + _multipleChoiceView.height + 40;
				_navBtn.enable( InteractiveEvent.SUBMIT_CHOICE );
			}
		
		}
		
		
		
		private function onBuildOutComplete( e:Event ):void {
			
			var event:String = _currentQuestion + 1 == _totalQuestions ? InteractiveEvent.GET_RESULTS : InteractiveEvent.NEXT_QUESTION; 
			_navBtn.enable( event );
		
		}
		
		
		
		private function onSubmitChoice( e:Event ):void {
			
			var isCorrect:Boolean = _currentChoice == Question( _questions[_currentQuestion] ).answer;
			var resultTxt:String = isCorrect ? Config.COPY.correct.toString() : Config.COPY.incorrect.toString();
			
			_questionField.testMetrics( resultTxt, 75, Config.PROJECT_XML.headerText2.@size );
			
			_responseDisplay.y = _questionField.y + _questionField.fieldHeight + 20;  
			_responseDisplay.setRespose( Question( _questions[_currentQuestion] ).response );
			
			_multipleChoiceView.buildOut();
			_navBtn.disable();
			
			_results.addResponse( Question( _questions[_currentQuestion] ).id, _currentChoice, isCorrect );
		
		}
		
		
		
		private function onNextQuestion( e:Event ):void {
			
			nextQuestion();
			_navBtn.disable();
			_responseDisplay.buildOut();
		
		}
		
		
		
		private function onGetResults( e:Event ):void {
			
			_navBtn.disable( );
			_responseDisplay.buildOut();
			_responseDisplay.addEventListener( InteractiveEvent.BUILD_OUT_COMPLETE, onResponseBuildOut );
		
		}
		
		
		
		private function onResponseBuildOut( e:Event ):void {
			
			var percent:Number = _results.totalPercentage;
			var copy:XML = Config.COPY;
			
			var message:String = 
                ( percent <= 25 ) ? copy.response1 :
                ( percent <= 50 ) ? copy.response2 :
				( percent <= 75 ) ? copy.response3 :
				( percent < 100 ) ? copy.response4 : 
				copy.response5;
			
			_questionField.testMetrics( message, 75, Config.PROJECT_XML.headerText2.@size );
			
			_responseDisplay.y = _questionField.y + _questionField.fieldHeight + 20;
			
			_responseDisplay.setRespose(
                "<font size='20'>" + copy.part1 + "</font><br />" +
                "<font size='16'>" + copy.part2+ ": "+_results.numCorrect + copy.part3.@between + _totalQuestions + "<br />" + 
                copy.part3 + ": " + _results.totalPercentage + "%</font>"
			);
			
			_responseDisplay.removeEventListener( InteractiveEvent.BUILD_OUT_COMPLETE, onResponseBuildOut );
			
			var loader:URLLoader = new URLLoader();
			loader.addEventListener( Event.COMPLETE, onLoadComplete );
			loader.addEventListener( IOErrorEvent.IO_ERROR, onError );
            /*loader.load(
                new URLRequest(
                    Config.PROJECT_XML.sumbitURLBase.toString() + 
                    "?email=" + UserInfoForm.USER_EMAIL + 
                    "&" + _results.getDataPairs()
                )
            );*/
		
		}
		
		
		
		private function onError( e:IOErrorEvent ):void {
		
		}
		
		
		
		private function onLoadComplete( e:Event ):void {
			
			e.target.removeEventListener( Event.COMPLETE, onLoadComplete );
		
		}
		
		
		
		private function onResetQuiz( e:Event ):void {
			
			_navBtn.disable();
			_responseDisplay.buildOut();
			_navBtn.removeEventListener( InteractiveEvent.RESET_QUIZ, onResetQuiz );
			parent.removeChild( this );
			dispatchEvent( e );
		
		}
		
		
		
		private function nextQuestion():void {
			
			_currentQuestion++;
			setQuestion( _currentQuestion );
		
		}
		
		
		
		private function checkText():void {
			
			if( _questionField.text.length <= 2 ) {
				_questionField.setFontSize( Config.PROJECT_XML.headerText2.@size );
			}
		
		}
		
		
		
	}
}